import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { getWindowHeight } from '@core/util/scroll-utils';
import { UploadFileUtilService } from '@core/routes-services/upload-file-util.service';
import { MyModalHelper } from '@core/my-modal.helper';
import { ConfirmComponent } from '@shared/confirm/confirm.component';
import { QCLOUD_DOMAIN } from '../../constant/config';


@Component({
  selector: 'full-screen-editor',
  templateUrl: './full-screen-editor.component.html',
  styleUrls: ['./full-screen-editor.component.scss'],
  providers: [UploadFileUtilService],
})
export class FullScreenEditorComponent implements OnInit {
  mot = false;
  showPic = true;
  showPic1 = false;
  event: any = null;
  eventDivId: any = null;

  qcloudDomain = QCLOUD_DOMAIN;
  //记录是否有修改数据，上下移、删除、上传操作后需要变成true,后续有更多关于内容的操作同样需要;
  componentDirty: boolean = false;

  //左上角按钮
  btns: any = '<div class="img-btns ignore-area" id="img-btns" style="position:absolute;width: 124px;height: 38px;border-radius: 4px;background-color: #fff;">' +
    '<div class="ignore-area img-btn-del" id="img-btn-del" title="删除" style="width: 23.33px;height: 22px;margin: 8px 0 8px 12px;float:left;cursor: pointer"><img class="ignore-area" src="../../../assets/img/delete1.png" alt=""></div>' +
    '<div class="ignore-area img-btn-up" id="img-btn-replace" title="替换" style="width: 23.33px;height: 22px;margin: 8px 0 8px 12px;float:left;cursor: pointer;"><img class="ignore-area" src="../../../assets/img/up1.png" alt=""></div>' +
    '<div class="ignore-area img-btn-up" id="img-btn-up" title="上移" style="width: 23.33px;height: 22px;margin: 8px 0 8px 12px;float:left;cursor: pointer;"><img class="ignore-area" src="../../../assets/img/up1.png" alt=""></div>' +
    '<div class="ignore-area img-btn-down" id="img-btn-down" title="下移" style="width: 23.33px;height: 22px;margin: 8px 0 8px 12px;float:left;cursor: pointer;"><img class="ignore-area" src="../../../assets/img/down1.png" alt=""></div>' +
    '</div>';

  //右侧竖排按钮
  verticalBtns: any = '<div class="img-btns ignore-area" id="img-btns" style="position:absolute;margin-left: 630px;width: 30px;height: 160px;border-radius: 4px;background-color: #fff;">' +
    '<div class="ignore-area img-btn-up" id="img-btn-up" title="上移" style="width: 23.33px;height: 22px;margin: 8px 0 8px 5px;float:left;cursor: pointer;"><img class="ignore-area" src="../../../assets/img/v_up1.png" alt=""></div>' +
    '<div class="ignore-area img-btn-down" id="img-btn-down" title="下移" style="width: 23.33px;height: 22px;margin: 8px 0 8px 5px;float:left;cursor: pointer;"><img class="ignore-area" src="../../../assets/img/v_down1.png" alt=""></div>'+
    '<div class="ignore-area img-btn-replace" id="img-btn-replace" title="替换" style="width: 23.33px;height: 22px;margin: 8px 0 8px 5px;float:left;cursor: pointer;"><img class="ignore-area" src="../../../assets/img/v_replace1.png" alt=""></div>' +
    '<div class="ignore-area img-btn-del" id="img-btn-del" title="删除" style="width: 30px;height: 22px;margin: 0px; border-top: 1px solid #808080; padding: 8px 0 0 5px; float:left;cursor: pointer"><img class="ignore-area" src="../../../assets/img/v_delete1.png" alt=""></div>' +
    '</div>';

  @Input() contentVal: any = '';

  @Output() close = new EventEmitter();
  @Output() contentCallback = new EventEmitter();


  @ViewChild('content') contentEl: ElementRef;
  @ViewChild('flag') flag: ElementRef;

  constructor(private uploadFileUtilService: UploadFileUtilService,
              private message: NzMessageService,
              private modalHelper: MyModalHelper) {
  }


  ngOnInit() {
    // console.log(this.contentVal);
    this.contentVal = this.contentVal ? this.contentVal : '';
    this.contentEl.nativeElement.innerHTML = this.contentVal;
    document.body.addEventListener('click', this.toShowBtn);
  }

  /**
   * 点击图显示操作按钮
   *
   * @param e
   */
  toShowBtn = (e) => {//<HTMLInputElement>
    let $this = this;
    let $Target = e.target;
    // console.log($Target)
    if ($Target.className.toString().includes('content-img')) {
      if ($Target.style.border && $Target.style.border != 'none') {
        $Target.style.border = 'none';
        document.getElementById('img-btns') ? document.getElementById('img-btns').remove() : null;
        $this.event = null;
      } else {
        $this.cleanOther();
        $this.event = e;
        $Target.style.border = '1px solid #108ee9';
        // console.log($Target.id);
        $this.eventDivId = $Target.id;
        let $inputDoc = document.getElementById('input' + this.eventDivId);
        if ($inputDoc) {
          $Target.parentNode.innerHTML = $this.verticalBtns.replace('添加图说明', '移除图说明') + $Target.parentNode.innerHTML;
        } else {
          $Target.parentNode.innerHTML = $this.verticalBtns + $Target.parentNode.innerHTML;
        }
        document.getElementById('img-btn-del').addEventListener('click', function(e) {
          $this.delImg(e);
        });
        document.getElementById('img-btn-replace').addEventListener('click', function(e) {
          $this.replaceImg(e);
        });
        document.getElementById('img-btn-up').addEventListener('click', function(e) {
          $this.upImg(e);
        });
        document.getElementById('img-btn-down').addEventListener('click', function(e) {
          $this.downImg(e);
        });
        // document.getElementById('img-btn-title').addEventListener('click', function (e) {
        //   $this.addTitle(e);
        // });
      }
    } else if ($Target.className.toString().includes('ignore-area')) {
      //不处理
    } else {
      $this.cleanOther();
    }

  };


  /**
   * 保存前清除按钮等无关内容
   */
  cleanOther() {
    let $this = this;
    let imgDom: any = document.getElementsByClassName('content-img');
    Array.prototype.forEach.call(imgDom, function(item, index, arr) {
      item.style.border = 'none';
      document.getElementById('img-btns') ? document.getElementById('img-btns').remove() : null;
      $this.event = null;
    });
  }

  upImg(e) {
    let children = document.getElementById('content').children;
    for (var i = 0; i < children.length; i++) {
      if (children[i].id == 'img' + this.eventDivId) {
        let previousNode = children[i].previousElementSibling;
        if (previousNode != null) {
          let parentNode = children[i].parentNode;
          parentNode.insertBefore(children[i], previousNode);
        }
        break;
      }
    }
    this.watchScroll();
    this.componentDirty = true;
  }

  downImg(e) {
    let children = document.getElementById('content').children;
    for (var i = 0; i < children.length; i++) {
      if (children[i].id == 'img' + this.eventDivId) {
        let nextNode = children[i].nextElementSibling;
        if (nextNode != null) {
          let parentNode = children[i].parentNode;
          parentNode.insertBefore(nextNode, children[i]);
        }
        break;
      }
    }
    this.watchScroll();
    this.componentDirty = true;
  }

  /**
   * 上移下移后滚动条处理
   */
  watchScroll() {
    let children = document.getElementById('content').children;
    let height = 0;
    for (var i = 0; i < children.length; i++) {
      if (children[i].id == 'img' + this.eventDivId) {
        $('#big_background').animate({ scrollTop: height - getWindowHeight() / 2 }, 'slow');
        break;
      } else {
        height += document.getElementById(children[i].id).getBoundingClientRect().height;
      }
    }
  }

  delImg(e) {
    let children = document.getElementById('content').children;
    for (var i = 0; i < children.length; i++) {
      if (children[i].id == 'img' + this.eventDivId) {
        children[i].remove();
        this.contentVal = this.contentEl.nativeElement.innerHTML;
      }
    }
    this.componentDirty = true;
  }

  orginType:any = 1;//1-无边距i 2有边距
  parentNode:Node = null;
  oldChild:Node = null;
  replaceImg(e) {
    let $this = this;
    let children = document.getElementById('content').children;
    for (var i = 0; i < children.length; i++) {
      if (children[i].id == 'img' + this.eventDivId) {
        $this.parentNode = children[i].parentNode;
        $this.oldChild = children[i];
        if(document.getElementById(children[i].id).style.margin){
          $this.orginType = 2
        }else {
          $this.orginType = 1
        }
          document.getElementById("replace-img-btn").click();
      }
    }
    this.componentDirty = true;
  }


  /**
   *  替换图回调
   *
   * @param event
   */
  toReplace(event: any) {
    // console.log(this)
    let $doc = document.getElementById("replace-img-btn");
    let $this = this;
    let files = event.target.files;
    for (let i = 0; i < files.length; i++) {// only one
      this.contentVal = this.contentEl.nativeElement.innerHTML;
      let file: any = files[i];
      this.uploadFileUtilService.uploadFile(file).then((resp: any) => {
        if (resp.status == 200) {
          let imgId = Number(new Date());
          let newChild:any = '';
          if ($this.orginType == 2) {
            newChild = '<div style="line-height: 0;margin: 10px;" id="img' + imgId + '">\n' +
              '<img  alt="加载失败" class="content-img" style="width: 100%; cursor: pointer; border: none;" src="' + $this.qcloudDomain + resp.data + '" id="' + imgId + '">\n' +
              ' </div>';
          } else {
            newChild = '<div style="line-height: 0;margin: 0px;" id="img' + imgId + '">\n' +
              '<img  alt="加载失败" class="content-img" style="width: 100%; cursor: pointer; border: none;" src="' + $this.qcloudDomain + resp.data + '" id="' + imgId + '">\n' +
              ' </div>';
          }
          $this.flag.nativeElement.innerHTML = newChild;
          $this.parentNode.replaceChild(document.getElementById("flag").children[0],$this.oldChild);
          $this.componentDirty = true;
          $this.contentVal = this.contentEl.nativeElement.innerHTML;
          document.getElementById(imgId.toString()).click();
        } else {
          $this.message.warning(resp.message);
        }
        $doc.setAttribute('type', 'text');
        $doc.setAttribute('type', 'file');
      }, error => {
        console.log('上传文件出错');
        $doc.setAttribute('type', 'text');
        $doc.setAttribute('type', 'file');
        $this.message.warning('上传文件出错请重新选择上传！');
      });
    }
  }


  /**
   * 关闭窗口前操作
   */
  beforClose() {
    this.cleanOther();
    this.close.emit(true);
    document.body.removeEventListener('click', this.toShowBtn);
  }

  /**
   * 提示
   */
  showConfirm = () => {
    if (this.componentDirty) {
      let $this = this;
      this.modalHelper.open(ConfirmComponent, { subtitle: '关闭将不会保存当前修改!' }, 500, {
        nzTitle: '<i class="anticon anticon-question-circle-o"></i>  确认关闭编辑窗口',
      }).subscribe(result => {
        if (result) {
          $this.beforClose();
        }
      }, (error) => {
        console.error('弹窗回调出错：', error);
      });
    } else {
      this.beforClose();
    }
  };


  toSave() {
    this.cleanOther();
    this.contentVal = this.contentEl.nativeElement.innerHTML;
    this.contentCallback.emit(this.contentVal);
    this.beforClose();
  }

  /**
   *帮助提示
   */
  showMot() {
    this.mot = !this.mot;
  }

  showActive() {
    this.showPic1 = !this.showPic1;
    if (this.showPic1) {
      this.showPic = false;
    }
  }

  showActive1() {
    this.showPic = !this.showPic;
    if (this.showPic) {
      this.showPic1 = false;
    }
  }


  /**
   *  上传图逻辑
   *
   * @param event
   * @param id
   * @param type 1-无边距i 2有边距
   */
  select(event: any, id, type) {
    // console.log(this)
    let $doc = document.getElementById(id);
    let $this = this;
    let files = event.target.files;
    for (let i = 0; i < files.length; i++) {
      this.contentVal = this.contentEl.nativeElement.innerHTML;
      let file: any = files[i];
      this.uploadFileUtilService.uploadFile(file).then((resp: any) => {
        if (resp.status == 200) {
          let imgId = Number(new Date());
          if (type == 2) {
            this.contentVal = this.contentVal + '<div style="line-height: 0;margin: 10px;" id="img' + imgId + '">\n' +
              '<img  alt="加载失败" class="content-img" style="width: 100%; cursor: pointer; border: none;" src="' + $this.qcloudDomain + resp.data + '" id="' + imgId + '">\n' +
              ' </div>';
          } else {
            this.contentVal = this.contentVal + '<div style="line-height: 0;margin: 0px;" id="img' + imgId + '">\n' +
              '<img  alt="加载失败" class="content-img" style="width: 100%; cursor: pointer; border: none;" src="' + $this.qcloudDomain + resp.data + '" id="' + imgId + '">\n' +
              ' </div>';
          }
          this.componentDirty = true;
          this.contentEl.nativeElement.innerHTML = this.contentVal;
        } else {
          this.message.warning(resp.message);
        }
        $doc.setAttribute('type', 'text');
        $doc.setAttribute('type', 'file');
      }, error => {
        console.log('上传文件出错');
        $doc.setAttribute('type', 'text');
        $doc.setAttribute('type', 'file');
        $this.message.warning('上传文件出错请重新选择上传！');
      });
    }
  }

}
